const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '.')));

// 数据库配置
const dbConfig = {
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'password',
    database: process.env.DB_NAME || 'social_app',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
};

// 创建连接池
const pool = mysql.createPool(dbConfig);

// JWT密钥
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-this';

// 认证中间件
const authenticateToken = async (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
        return res.status(401).json({ message: '需要登录' });
    }

    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        req.user = decoded;
        next();
    } catch (error) {
        return res.status(403).json({ message: '无效的token' });
    }
};

// 路由

// 用户注册
app.post('/api/auth/register', async (req, res) => {
    try {
        const { username, password } = req.body;

        if (!username || !password) {
            return res.status(400).json({ message: '用户名和密码不能为空' });
        }

        if (password.length < 6) {
            return res.status(400).json({ message: '密码长度至少6位' });
        }

        // 检查用户名是否已存在
        const [existingUsers] = await pool.execute(
            'SELECT id FROM users WHERE username = ?',
            [username]
        );

        if (existingUsers.length > 0) {
            return res.status(400).json({ message: '用户名已存在' });
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(password, 10);

        // 创建用户
        const [result] = await pool.execute(
            'INSERT INTO users (username, password, balance) VALUES (?, ?, ?)',
            [username, hashedPassword, 0.00]
        );

        const userId = result.insertId;
        const token = jwt.sign({ id: userId, username }, JWT_SECRET, { expiresIn: '7d' });

        res.json({
            token,
            user: {
                id: userId,
                username,
                balance: 0.00
            }
        });
    } catch (error) {
        console.error('注册错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 用户登录
app.post('/api/auth/login', async (req, res) => {
    try {
        const { username, password } = req.body;

        if (!username || !password) {
            return res.status(400).json({ message: '用户名和密码不能为空' });
        }

        // 查找用户
        const [users] = await pool.execute(
            'SELECT id, username, password, balance FROM users WHERE username = ?',
            [username]
        );

        if (users.length === 0) {
            return res.status(401).json({ message: '用户名或密码错误' });
        }

        const user = users[0];

        // 验证密码
        const isValidPassword = await bcrypt.compare(password, user.password);
        if (!isValidPassword) {
            return res.status(401).json({ message: '用户名或密码错误' });
        }

        const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '7d' });

        res.json({
            token,
            user: {
                id: user.id,
                username: user.username,
                balance: parseFloat(user.balance)
            }
        });
    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取当前用户信息
app.get('/api/auth/me', authenticateToken, async (req, res) => {
    try {
        const [users] = await pool.execute(
            'SELECT id, username, balance FROM users WHERE id = ?',
            [req.user.id]
        );

        if (users.length === 0) {
            return res.status(404).json({ message: '用户不存在' });
        }

        const user = users[0];
        res.json({
            user: {
                id: user.id,
                username: user.username,
                balance: parseFloat(user.balance)
            }
        });
    } catch (error) {
        console.error('获取用户信息错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 发布动态
app.post('/api/posts', authenticateToken, async (req, res) => {
    try {
        const { content } = req.body;

        if (!content || content.trim().length === 0) {
            return res.status(400).json({ message: '内容不能为空' });
        }

        const [result] = await pool.execute(
            'INSERT INTO posts (user_id, content) VALUES (?, ?)',
            [req.user.id, content.trim()]
        );

        res.json({
            message: '发布成功',
            post: {
                id: result.insertId,
                content: content.trim(),
                user_id: req.user.id,
                username: req.user.username,
                created_at: new Date()
            }
        });
    } catch (error) {
        console.error('发布动态错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取动态列表
app.get('/api/posts', async (req, res) => {
    try {
        const [posts] = await pool.execute(`
            SELECT p.id, p.content, p.created_at, p.likes, p.comments,
                   u.username
            FROM posts p
            JOIN users u ON p.user_id = u.id
            ORDER BY p.created_at DESC
            LIMIT 50
        `);

        res.json({
            posts: posts.map(post => ({
                id: post.id,
                content: post.content,
                username: post.username,
                created_at: post.created_at,
                likes: post.likes || 0,
                comments: post.comments || 0
            }))
        });
    } catch (error) {
        console.error('获取动态列表错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 充值
app.post('/api/payments/recharge', authenticateToken, async (req, res) => {
    try {
        const { amount, payment_method } = req.body;

        if (!amount || amount <= 0) {
            return res.status(400).json({ message: '充值金额无效' });
        }

        // 模拟支付处理
        const [result] = await pool.execute(
            'UPDATE users SET balance = balance + ? WHERE id = ?',
            [amount, req.user.id]
        );

        // 记录充值记录
        await pool.execute(
            'INSERT INTO payments (user_id, amount, payment_method, status) VALUES (?, ?, ?, ?)',
            [req.user.id, amount, payment_method, 'completed']
        );

        res.json({
            message: '充值成功',
            amount: amount
        });
    } catch (error) {
        console.error('充值错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 健康检查
app.get('/api/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 启动服务器
async function startServer() {
    try {
        // 测试数据库连接
        await pool.execute('SELECT 1');
        console.log('数据库连接成功');
        
        app.listen(PORT, () => {
            console.log(`服务器运行在端口 ${PORT}`);
            console.log(`访问地址: http://localhost:${PORT}`);
        });
    } catch (error) {
        console.error('数据库连接失败:', error);
        process.exit(1);
    }
}

startServer();
